package com.jctrip.hotel.common.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: zxy
 * @CreateTime: 2023-08-27 17:53
 * @Description:
 */
@Component
@Slf4j
public class OssUtil implements InitializingBean {

    private static String endpoint;

    private static String accessKeyId;

    private static String accessKeySecret;

    private static String bucketName ;

    private static String endpointInside;

    private static String prefix;

    private static String picPrefix;

    private static String domain;

    @Value("${aliyun.oss.endPoint}")
    private String ENDPOINT;

    @Value("${aliyun.oss.endPointInside}")
    private String ENDPOINTINSIDE;

    @Value("${aliyun.oss.accessKeyId}")
    private String ACCESSKEYID;

    @Value("${aliyun.oss.accessKeySecret}")
    private String ACCESSKEYSECRET;

    @Value("${aliyun.oss.bucketName}")
    private String BUCKNAME ;

    @Value("${aliyun.oss.dir.prefix}")
    private String PREFIX ;

    @Value("${aliyun.oss.dir.pic-prefix}")
    private String PICPREFIX;

    @Value("${aliyun.oss.domain}")
    private String DOMAIN;


    public static String updaload(byte[] content) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileName;
        try {
            fileName = String.format("%s%s/订单列表-%d.xlsx", prefix,
                    new SimpleDateFormat("yyyy-MM").format(new Date()),
                    System.currentTimeMillis());
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(content));
            // 创建PutObject请求。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
            fileName = "error";
        } catch (ClientException ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
            fileName = "error";
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileName;
    }

    public static String updaload(byte[] content, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String target;
        try {
            target = picPrefix + fileName;
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, target, new ByteArrayInputStream(content));
            // 创建PutObject请求。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
            target = null;
        } catch (ClientException ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
            target = null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return target;
    }

    public static String updaload(String url, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String target;
        try {
            target = picPrefix + fileName;
            InputStream inputStream = null;
            try {
                inputStream = new URL(url).openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, target, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            target = null;
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            target = null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return target;
    }

    public static URL download(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpointInside, accessKeyId, accessKeySecret);
        URL url = null;
        try {
            // Url有效期为1小时
            Date expiration = new Date(new Date().getTime() + 3600L * 60);
            url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }

    public static String downloadPic(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = null;
        URL url = null;
        try {
            // Url有效期为1小时
            Date expiration = new Date(new Date().getTime() + 3600L * 60);
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            // 开启CNAME。CNAME用于将自定义域名绑定到目标Bucket。
            conf.setSupportCname(true);
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(domain, accessKeyId, accessKeySecret, conf);
            url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url.toString();
    }

    public static void delete(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, " +
                    "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        endpoint = ENDPOINT;
        accessKeyId = ACCESSKEYID;
        accessKeySecret = ACCESSKEYSECRET;
        bucketName = BUCKNAME;
        prefix = PREFIX;
        endpointInside = ENDPOINTINSIDE;
        picPrefix = PICPREFIX;
        domain = DOMAIN;
    }
}
